import { getDataByLocal, setData2Local } from "./localStore";
import { getDataByStore, setData2Store } from "./store";

const _time = 60 * 60 * 1000;
export const Store = function(tag: string, time: number = _time) {
  return function(_target: any, pro: string, descriptor: PropertyDescriptor) {
    const oldMethods = descriptor.value;
    descriptor.value = function(...args: any[]) {
      const promise = new Promise((resolve, reject) => {
        const key = `${pro}_${tag}_${JSON.stringify([...args])}`;
        const data = getDataByStore(key);
        if (data) {
          resolve(data);
        } else {
          oldMethods
            .apply(this, args)
            .then((res: any) => {
              setData2Store({ time, data: res, key });
              resolve(res);
            })
            .catch((e: Error) => {
              reject(e);
            });
        }
      });
      return promise;
    };
    return descriptor;
  };
};
export const SessionStore = function(time: number = _time) {};
// 修饰器，用于localStorage
export const LocalStore = function(tag: string, time: number = _time) {
  return function(_target: any, pro: string, descriptor: PropertyDescriptor) {
    const oldMethods = descriptor.value;
    descriptor.value = function(...args: any[]) {
      const promise = new Promise((resolve, reject) => {
        const key = `${pro}_${tag}_${JSON.stringify([...args])}`;
        const data = getDataByLocal(key);
        if (data) {
          resolve(data);
        } else {
          oldMethods
            .apply(this, args)
            .then((res: any) => {
              setData2Local({ time, data: res, key });
              resolve(res);
            })
            .catch((e: Error) => {
              reject(e);
            });
        }
      });
      return promise;
    };
    return descriptor;
  };
};
